package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.entity.CmsSuppliersTempEntity;
import com.yuanda.erp9.syn.enums.*;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.poi.ICGooCsvData;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.pojo.CmsPricesPojo;
import com.yuanda.erp9.syn.service.erp9.ICGooDataImportService;
import com.yuanda.erp9.syn.util.CsvReadUtils;
import com.yuanda.erp9.syn.util.DateUtils;
import com.yuanda.erp9.syn.util.EasyExcelUtils;
import com.yuanda.erp9.syn.util.RateCalculateUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @desc   ICGoo数据导入的实现类
 * @author linuo
 * @time   2022年11月30日16:37:28
 */
@Service
@Slf4j
public class ICGooDataImportServiceImpl extends CsvSaveImpl implements ICGooDataImportService {
    /** 供应商名称 */
    private static final String SUPPLIER = "Cycle-chips Components Inc.";

    /** 供应商id */
    private static final String SUPPLIER_ID = "US000008311";

    /** 判断字符串是否为数据的正则规则 */
    private static final Pattern pattern = Pattern.compile("-?[0-9]+(\\\\.[0-9]+)?");

    /**
     * 导入ICGoo文件数据
     * @param topicUpdateLogId 系统主体更新日志记录表id
     * @param filePath 文件路径
     */
    @Override
    public String importCmsGoodsPojo(Long topicUpdateLogId, String filePath) {
        Integer supplierId = suppliersCache.get(SUPPLIER);
        if(supplierId == null){
            // 插入供应商数据
            CmsSuppliersTempEntity cmsSuppliersTempEntity = new CmsSuppliersTempEntity();
            cmsSuppliersTempEntity.setSupplierUs(SUPPLIER_ID);
            cmsSuppliersTempEntity.setName(SUPPLIER);
            cmsSuppliersTempEntity.setTag(0);
            int insert = cmsSuppliersTempMapper.insert(cmsSuppliersTempEntity);
            if(insert > 0){
                supplierId = cmsSuppliersTempEntity.getSupplierid();
            }
        }

        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, null, SourceEnum.DATA_PACKAGE.getCode());

        try {
            // 读取csv数据
            List<String[]> strings = CsvReadUtils.parseCSV(filePath);
            if(strings != null && strings.size() > 0){
                if(topicUpdateLogId != null){
                    // 插入系统主体更新数量日志记录表数据
                    Integer integer = cmsTopicUpdateSumLogService.insertBySum((long) strings.size(), topicUpdateLogId);
                    if(integer > 0){
                        log.info("插入系统主体更新数量日志记录表数据成功");
                    }
                }

                log.info("创建ICGoo数据导入任务开始");
                for (int i = 0; i < strings.size(); i++) {
                    String[] string = strings.get(i);
                    ICGooCsvData icGooCsvData = ICGooCsvData.toICGooCsvDataFormat(string, i);
                    if (Strings.isNullOrEmpty(icGooCsvData.getBrand())) {
                        continue;
                    }

                    if (string.length == 30) {
                        try {
                            CmsGoodsPojo cmsGoodsPojo = packageCmsGoodsPojo(icGooCsvData, supplierId);
                            objectMaster.add(cmsGoodsPojo);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }finally {
            objectMaster.isBegin = false;
        }

        log.info("创建ICGoo数据导入任务结束");
        return "ok";
    }

    /**
     * Waldom数据组装
     * @param icGooCsvData ICGoo数据解析
     */
    private CmsGoodsPojo packageCmsGoodsPojo(ICGooCsvData icGooCsvData, Integer supplierId) {
        CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();

        CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();

        cmsGoodsEntity.setAdminid(0);
        cmsGoodsEntity.setTenantsid(0);

        // 库存
        Integer inventory = icGooCsvData.getInventory();
        if(inventory == null){
            inventory = 0;
        }else{
            // 上下浮动5%，取0.95和1.05的随机数，然后乘以本身库存量并向上取整
            BigDecimal random = getRandom(0.95f, 1.05f);
            BigDecimal multiply = BigDecimal.valueOf(inventory).multiply(random);
            BigDecimal bigDecimal = multiply.setScale(0, BigDecimal.ROUND_UP);
            inventory = bigDecimal.intValue();
        }

        // 型号
        String model = icGooCsvData.getModel();

        // 品牌
        String brand = icGooCsvData.getBrand();

        // 批次
        String batch = icGooCsvData.getBatch();

        // 最小起订量
        Long moq = icGooCsvData.getMoq();
        if(moq == null){
            moq = 1L;
        }

        // 处理批次号
        batch = handleBatch(batch);

        // 生成sign
        //String sign = DigestUtils.md5DigestAsHex((model + brand + packaging + batch + moq + inventory + channelCode + row).getBytes());
        String sign = "WangSQ" + "_" + model + "_" + icGooCsvData.getRow();

        // 供应商id
        cmsGoodsEntity.setSupplier(supplierId);

        // 产品唯一标识
        String incodes = EasyExcelUtils.getIncodes(sign, SUPPLIER_ID, "", "", "", "", "", cmsGoodsEntity.getSupplier());
        cmsGoodsEntity.setIncodes(incodes);
        cmsGoodsEntity.setGoodid(incodes);

        cmsGoodsEntity.setClassifyid(0);
        cmsGoodsEntity.setImg("");
        cmsGoodsEntity.setType(0);
        cmsGoodsEntity.setStatus(1);
        cmsGoodsEntity.setStatusMsg(null);
        cmsGoodsEntity.setDataType(1);
        cmsGoodsEntity.setModel(model);

        // 处理品牌信息，缓存中没有当前品牌时添加信息到数据库和缓存中
        Integer i = brandCache.get(brand);
        if (i == null) {
            // 插入品牌数据
            Integer brandId = insertBrand(brand);
            cmsGoodsEntity.setBrand(brandId);
        }else{
            cmsGoodsEntity.setBrand(i);
        }

        cmsGoodsEntity.setBatch(batch);
        cmsGoodsEntity.setIsSampleApply(0);
        cmsGoodsEntity.setOriginalPrice(BigDecimal.ZERO);
        cmsGoodsEntity.setPurchasePrice(BigDecimal.ZERO);

        // 库存
        cmsGoodsEntity.setRepertory(inventory);

        // 库存所在地
        cmsGoodsEntity.setRepertoryArea("");

        cmsGoodsEntity.setPublish(1);

        // 购买类型0单个买1整包买
        cmsGoodsEntity.setPayType(0);

        // 增量
        cmsGoodsEntity.setIncremental(1L);

        // mpq
        cmsGoodsEntity.setMpq(StringUtils.isEmpty(icGooCsvData.getMoq()) ? 1 : icGooCsvData.getMoq());

        // 交货地区
        if(!Strings.isNullOrEmpty(icGooCsvData.getCurrency()) && "人民币含税".equals(icGooCsvData.getCurrency())){
            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.DOMESTIC.getCode());

            // 国内交货日期
            cmsGoodsEntity.setDomesticDate("5-7个工作日");

        }else if(!Strings.isNullOrEmpty(icGooCsvData.getCurrency()) && "留港美金".equals(icGooCsvData.getCurrency())){
            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());

            // 国内交货日期
            cmsGoodsEntity.setDomesticDate("5-7个工作日");
            cmsGoodsEntity.setHongkongDate("3-5个工作日");
        }else{
            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());

            // 国内交货日期
            cmsGoodsEntity.setDomesticDate("5-7个工作日");
            cmsGoodsEntity.setHongkongDate("3-5个工作日");
        }

        cmsGoodsEntity.setHisp("WangSQ");

        // 是否需要3c认证
        cmsGoodsEntity.setCcc(WhetherOrNotEnum.NO.getCode());

        cmsGoodsEntity.setSales(0);
        cmsGoodsEntity.setClick(0);
        cmsGoodsEntity.setVisitor(0);

        cmsGoodsEntity.setCreatedAt(DateUtils.now());
        cmsGoodsEntity.setUpdatedAt(DateUtils.now());

        cmsGoodsEntity.setInspectionChargesFee(0D);

        cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
        cmsGoodsEntity.setSplName(SUPPLIER);
        cmsGoodsEntity.setBrandName(brand);

        if(null == cmsGoodsEntity.getBatch()){
            cmsGoodsEntity.setBatch("");
        }

        Integer currency;
        String currencyDesc = icGooCsvData.getCurrency();
        if("人民币含税".equals(currencyDesc)){
            currency = CurrencyEnum.RMB.getCode();
        }else{
            currency = CurrencyEnum.DOLLAR.getCode();
        }

        // 组装阶梯价格
        List<CmsPricesEntity> list = createCmsPrices(currency, cmsGoodsEntity.getGoodid(), icGooCsvData);
        cmsGoodsPojo.setCmsPricesEntityList(list);

        // 根据渠道和最低阶梯价格计算最小起订量
        Long minimumOrder = calculateMinimumOrderByChannel(currency, icGooCsvData.getBjPriceBreak1(), icGooCsvData.getChannelCode());
        if(minimumOrder != null && minimumOrder > moq){
            moq = minimumOrder;
        }

        // 最小起订
        cmsGoodsEntity.setMinimumOrder(getMoqByLadderPriceList(moq, list));

        // 原始库存量
        Integer inventory1 = icGooCsvData.getInventory();
        if(inventory1 == null){
            inventory1 = 0;
        }

        // 计算单价
        //cmsGoodsEntity.setUnitPrice(calculateUnitPrice(list));

        // 计算出来的最小起订量
        Long minimumOrder1 = cmsGoodsEntity.getMinimumOrder();

        List<CmsPricesPojo> prices = new ArrayList<>();
        for(CmsPricesEntity cmsPricesEntity : list){
            CmsPricesPojo cmsPricesPojo = new CmsPricesPojo();
            BeanUtils.copyProperties(cmsPricesEntity, cmsPricesPojo);
            prices.add(cmsPricesPojo);
        }

        // 判断计算出来的最小起订量大于原始库存量，价格赋空
        if(minimumOrder1 != null && minimumOrder1.intValue() > inventory1.intValue()){
            cmsGoodsEntity.setPrices(null);
        }else{
            // 更新阶梯价格配置到商品表
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(prices, SerializerFeature.WriteMapNullValue));
            if(!jsonArray.isEmpty()){
                cmsGoodsEntity.setPrices(jsonArray.toString());
            }
        }

        // 费率
        JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());

        // 从费率的json中获取信息补充到商品表实体中
        cmsGoodsEntity = addRateInfo(cmsGoodsEntity, data);

        // 封装
        cmsGoodsEntity.setPackage_(icGooCsvData.getPackaging());

        cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);

        // 组装商品表-副表信息
        cmsGoodsPojo.setCmsGoodsInformationEntity(createCmsGoodsInformation(cmsGoodsEntity.getGoodid(), cmsGoodsEntity.getInspectionChargesFee()));

        return cmsGoodsPojo;
    }

    /**
     * 处理批次号
     * @param batch 批次号
     * @return 返回处理结果
     */
    private String handleBatch(String batch) {
        if(batch.length() >= 2 && batch.endsWith("+")){
            String data = batch;
            data = data.replace("+", "");

            Matcher matcher = pattern.matcher(data);
            // 判断去除加号的字符串是否为数据且长度为2
            if(data.length() == 1 && matcher.matches()){
                return "0" + data + "+";
            }

            if(data.length() == 2 && matcher.matches()){
                return data + "+";
            }

            return "";
        }else{
            batch = "";
        }
        return batch;
    }

    /**
     * 根据渠道和最低阶梯价格计算最小起订量
     * @param currency 币种
     * @param price 最低阶梯价格
     * @param channelCode 渠道代码
     * @return 返回计算出来的最小起订量
     */
    private Long calculateMinimumOrderByChannel(Integer currency, String price, String channelCode) {
        Long result = null;
        if(!Strings.isNullOrEmpty(price) && !Strings.isNullOrEmpty(channelCode)){
            SuppliersMinimumAmountEnum suppliersMinimumAmountEnum = SuppliersMinimumAmountEnum.of(channelCode);
            if(suppliersMinimumAmountEnum != null){
                Integer money = suppliersMinimumAmountEnum.getMoney();

                Integer enumCurrency;
                if("RMB".equals(suppliersMinimumAmountEnum.getCurrency())){
                    enumCurrency = CurrencyEnum.RMB.getCode();
                }else{
                    enumCurrency = CurrencyEnum.DOLLAR.getCode();
                }

                if(currency.intValue() == enumCurrency.intValue()){
                    price = handlePriceBreak(price);

                    BigDecimal bigDecimal = BigDecimal.valueOf(Long.parseLong(money.toString()));
                    BigDecimal divide = bigDecimal.divide(new BigDecimal(price), 0, BigDecimal.ROUND_UP);
                    if(divide != null && divide.intValue() > 0){
                        result = divide.longValue();
                    }
                }
            }
        }
        return result;
    }

    /**
     * 获取区间范围内的随机数
     * @param minValue 最小值
     * @param maxValue 最大值
     * @return 返回计算结果
     */
    public static BigDecimal getRandom(float minValue, float maxValue){
        BigDecimal min = BigDecimal.valueOf(minValue).multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP);
        BigDecimal max = BigDecimal.valueOf(maxValue).multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP);

        Random random = new Random();
        // 获取随机数
        int s = random.nextInt(max.intValue()) % (max.intValue() - min.intValue() + 1) + min.intValue();
        return BigDecimal.valueOf(s).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 组装阶梯价格信息
     * @param currency 币种
     * @param icGooCsvData ICGoo数据解析
     */
    private List<CmsPricesEntity> createCmsPrices(Integer currency, String goodId, ICGooCsvData icGooCsvData) {
        List<CmsPricesEntity> result = new ArrayList<>();

        Long bjQtyBreak1 = icGooCsvData.getBjQtyBreak1();
        String bjPriceBreak1 = icGooCsvData.getBjPriceBreak1();
        Long bjQtyBreak2 = icGooCsvData.getBjQtyBreak2();

        int position = 0;
        Long max;

        // 一级阶梯价格
        if(null != bjQtyBreak1 && !Strings.isEmpty(bjPriceBreak1)){

            if(null != bjQtyBreak2){
                max = bjQtyBreak2 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, bjQtyBreak1, max, bjPriceBreak1, currency, position));
            position = position + 1;
        }

        // 二级阶梯价格
        String bjPriceBreak2 = icGooCsvData.getBjPriceBreak2();
        Long bjQtyBreak3 = icGooCsvData.getBjQtyBreak3();
        if(null != bjQtyBreak2 && !Strings.isEmpty(bjPriceBreak2)){

            if(null != bjQtyBreak3){
                max = bjQtyBreak3 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, bjQtyBreak2, max, bjPriceBreak2, currency, position));
            position = position + 1;
        }

        // 三级阶梯价格
        String bjPriceBreak3 = icGooCsvData.getBjPriceBreak3();
        Long bjQtyBreak4 = icGooCsvData.getBjQtyBreak4();
        if(null != bjQtyBreak3 && !Strings.isEmpty(bjPriceBreak3)){

            if(null != bjQtyBreak4){
                max = bjQtyBreak4 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, bjQtyBreak3, max, bjPriceBreak3, currency, position));
            position = position + 1;
        }

        // 四级阶梯价格
        String bjPriceBreak4 = icGooCsvData.getBjPriceBreak4();
        Long bjQtyBreak5 = icGooCsvData.getBjQtyBreak5();
        if(null != bjQtyBreak4 && !Strings.isEmpty(bjPriceBreak4)){

            if(null != bjQtyBreak5){
                max = bjQtyBreak5 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, bjQtyBreak4, max, bjPriceBreak4, currency, position));
            position = position + 1;
        }

        // 五级阶梯价格
        String bjPriceBreak5 = icGooCsvData.getBjPriceBreak5();
        Long bjQtyBreak6 = icGooCsvData.getBjQtyBreak6();
        if(null != bjQtyBreak5 && !Strings.isEmpty(bjPriceBreak5)){

            if(null != bjQtyBreak6){
                max = bjQtyBreak6 - 1;
            }else{
                max = 0L;
            }

            result.add(createCmsPriceData(goodId, bjQtyBreak5, max, bjPriceBreak5, currency, position));
            position = position + 1;
        }

        // 六级阶梯价格
        String bjPriceBreak6 = icGooCsvData.getBjPriceBreak6();
        if(null != bjQtyBreak6 && !Strings.isEmpty(bjPriceBreak6)){
            result.add(createCmsPriceData(goodId, bjQtyBreak6, 0L, bjPriceBreak6, currency, position));
        }

        // 组装阶梯价格list、根据商品id更新阶梯价格字段内容
        return result;
    }
}